package com.demo.system.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.common.entity.ChatRoom;
import com.demo.common.entity.ChatRoomMember;
import com.demo.common.entity.vo.ChatRoomMemberVO;
import com.demo.common.response.Result;
import com.demo.system.mapper.ChatRoomMemberMapper;
import com.demo.system.service.ChatRoomMemberService;
import com.demo.system.service.ChatRoomService;
import com.demo.system.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 聊天室成员表(ChatRoomMember)
 *
 * @author why
 * @since 2025-09-23 10:12:43
 */
@Service("chatRoomMember")
@RequiredArgsConstructor
public class ChatRoomMemberServiceImpl extends ServiceImpl<ChatRoomMemberMapper, ChatRoomMember> implements ChatRoomMemberService {


    private final ChatRoomService chatRoomService;
    private final UserService userService;

    @Override
    public Result<List<ChatRoomMemberVO>> listRoomByUserId(String userId) {
        List<ChatRoomMemberVO> Rooms = baseMapper.listRoomByUserId(new QueryWrapper<ChatRoomMemberVO>().eq("a.user_id", userId).orderByDesc(" a.join_time"));
        if (CollUtil.isEmpty(Rooms)) {
            return Result.error("暂未加入群聊");
        }
        return Result.success(Rooms);
    }


    @Override
    public Result joinChatRoom(Long userId, Long roomId) {
        ChatRoomMember member = new ChatRoomMember();
        member.setUserId(userId);
        member.setRoomId(roomId);
        member.setJoinTime(new Date());
        member.setIsMuted(0);
        member.setIsActive(1);
        save(member);
        return Result.success();
    }

    @Override
    public Result<List<ChatRoom>> findOtherRoomByUserId(String userId) {
        List<ChatRoomMember> joinRooms = list(new LambdaQueryWrapper<ChatRoomMember>().eq(ChatRoomMember::getUserId, userId));
        if (CollUtil.isEmpty(joinRooms)) {
            return Result.success(chatRoomService.list());
        }
        List<Long> list = joinRooms.stream().map(ChatRoomMember::getRoomId).toList();
        List<ChatRoom> rooms = chatRoomService.list(new LambdaQueryWrapper<ChatRoom>().notIn(ChatRoom::getId, list));
        return Result.success(rooms);
    }


}





